package com.web;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import lombok.SneakyThrows;

import java.io.File;
import java.util.Map;

/**
 * 通过Jackson读取、写入yaml文件
 *
 * @author：zhang guoxiang
 * @date：2022/4/15
 */
public abstract class YamlUtils {

    private static final ObjectMapper OBJECT_READ_MAPPER = new ObjectMapper(new YAMLFactory())
            .findAndRegisterModules().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    private static final ObjectMapper OBJECT_WRITE_MAPPER = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER))
            .findAndRegisterModules().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @SneakyThrows
    public static void write(File file, Object obj) {
        OBJECT_WRITE_MAPPER.writeValue(file, obj);
    }

    public static void write(String filePath, Object obj) {
        write(new File(filePath), obj);
    }

    @SneakyThrows
    public static <T> T load(File file, Class<T> tClass) {
        return OBJECT_READ_MAPPER.readValue(file, tClass);
    }

    @SneakyThrows
    public static Map<String, Object> load(File file) {
        return OBJECT_READ_MAPPER.readValue(file, new TypeReference<Map<String, Object>>() {
        });
    }

    @SneakyThrows
    public static <T> T load(File file, TypeReference<T> ref) {
        return OBJECT_READ_MAPPER.readValue(file, ref);
    }


}
